package com.action;

import org.apache.commons.codec.binary.Base64;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.util.AuthenticationUtils;
import com.util.AuthenticationUtils.License;

/**
 * Authenticates license key.
 * 
 * @author Anthony.M
 *
 */
public class AuthenticationAction extends ActionSupport {

	private static final long serialVersionUID = 726190926844059333L;

	public static final class Page {

		private boolean success;
		private String message;
		private License license;

		public boolean isSuccess() {
			return success;
		}

		public void setSuccess(boolean success) {
			this.success = success;
		}

		public String getMessage() {
			return message;
		}

		public void setMessage(String message) {
			this.message = message;
		}

		public License getLicense() {
			return license;
		}

		public void setLicense(License license) {
			this.license = license;
		}

	}

	private Page page;

	private String licenseKey;

	public Page getPage() {
		return page;
	}

	public void setLicenseKey(String licenseKey) {
		this.licenseKey = licenseKey;
	}

	public String setupLicense() throws Exception {
		String serverId = AuthenticationUtils.getServerId(AuthenticationUtils.getMacAddress());
		ActionContext.getContext().put("serverId", serverId);
		try {
			byte[] key = AuthenticationUtils.loadLicenseKey();
			License license = AuthenticationUtils.parseLicenseKey(key);
			ActionContext.getContext().put("license", license);
		} catch (Exception e) {
		}
		return SUCCESS;
	}

	public String installOrUpdateLicense() throws Exception {
		page = new Page();
		License license = null;
		try {
			byte[] key = Base64.decodeBase64(licenseKey.getBytes());
			license = AuthenticationUtils.parseLicenseKey(key);
			AuthenticationUtils.saveLicenseKey(key);
		} catch (Exception e) {
			e.printStackTrace();
			page.setSuccess(false);
			page.setMessage(e.getMessage());
			return SUCCESS;
		}
		ActionContext.getContext().getSession().put("license", license);
		page.setSuccess(true);
		page.setMessage("License installed");
		page.setLicense(license);
		return SUCCESS;
	}

}
